package com.passion.mq.transaction;

import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 类描述：
 *
 * @author ZhuYin
 * @since 2024年12月30日
 */
@Slf4j
@Service
@ConditionalOnBean(RocketMQTemplate.class)
@RocketMQTransactionListener
public class TransactionalMessageService implements RocketMQLocalTransactionListener {

    @Autowired(required = false)
    private RocketMQTemplate rocketMQTemplate;

    public void sendMessageInTransaction(String topic, String messageBody) {
        Message<String> message = MessageBuilder
                .withPayload(messageBody)
                .setHeader(RocketMQHeaders.TRANSACTION_ID, UUID.fastUUID())
                .build();
        rocketMQTemplate.sendMessageInTransaction(topic, message, null);
    }

    public void sendMessageInTransactionWithProperties(String topic, String messageBody, Map<String, Object> properties) {
        Message<String> message = MessageBuilder
                .withPayload(messageBody)
                .setHeader(RocketMQHeaders.TRANSACTION_ID, UUID.fastUUID())
                // 添加所有属性作为消息头
                .copyHeaders(properties)
                .build();
        rocketMQTemplate.sendMessageInTransaction(topic, message, null);
    }

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        // 根据本地事务的结果返回不同的状态
        RocketMQLocalTransactionState state = checkLocalTransaction(message);
        return state;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        // 检查本地事务状态
        // ...
        try {
            // ...
            int i = 1/0;
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            log.error("本地事务异常：", e);
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
    
}